from PyQt5.QtCore import Qt, QPropertyAnimation
from PyQt5.QtGui import QColor, QBitmap, QPainter
from PyQt5.QtWidgets import QWidget, QGraphicsDropShadowEffect


class BaseWindow(QWidget):
    """基础 Window"""

    def __init__(self):
        super().__init__()
        self.SHADOW_WIDTH = 8

    def redirect(self, window):
        """重定向到某个窗口"""
        pass

    def signal_binder(self):
        """信号绑定"""
        pass

    def qss_render(self):
        """QSS 渲染器，有定义 QSS 则加载"""
        if self.qss:
            self.setStyleSheet(self.qss_loader())

    def qss_loader(self):
        """QSS 加载器"""
        with open(self.qss, "r", encoding="utf8") as f:
            return f.read()

    def get_shadow(self, rgb: tuple, r: int, offset=(0, 0)):
        """按键阴影"""

        effect_shadow = QGraphicsDropShadowEffect(self)
        effect_shadow.setOffset(*offset)  # 偏移
        effect_shadow.setBlurRadius(r)  # 阴影半径
        effect_shadow.setColor(QColor(*rgb))  # 阴影颜色
        return effect_shadow

    def set_circle(self):
        """窗口圆角"""
        bitmap = QBitmap(self.size())
        bitmap.fill()
        painter = QPainter(bitmap)
        painter.begin(self)
        painter.setPen(Qt.NoPen)
        painter.setBrush(Qt.black)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.drawRoundedRect(bitmap.rect(), 5, 5)
        painter.end()
        self.setMask(bitmap)


class FadeOutWindow(BaseWindow):
    """淡出窗口"""
    close_animation = None

    def closeEvent(self, event):
        if self.close_animation is None:
            self.setWindowOpacity(1)

            self.close_animation = QPropertyAnimation(self, b'windowOpacity')
            self.close_animation.setDuration(500)
            self.close_animation.setStartValue(1)
            self.close_animation.setEndValue(0.1)
            self.close_animation.finished.connect(self.close)
            self.close_animation.start()
            event.ignore()


class NoBorderWindow(FadeOutWindow):
    """无边框窗口类"""

    def __init__(self):
        super().__init__()

        self.mouse_flag = ""
        self.mouse_position = ""
        self.setWindowFlags(Qt.FramelessWindowHint)  # 无边框
        self.set_circle()  # 圆角

    def mousePressEvent(self, event):
        """ 无边框可移动组件1 """
        if event.button() == Qt.LeftButton:
            self.mouse_flag = True
            self.mouse_position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()

    def mouseMoveEvent(self, event):
        """ 无边框可移动组件2 """
        if Qt.LeftButton and self.mouse_flag:
            self.move(event.globalPos() - self.mouse_position)  # 更改窗口位置
            event.accept()

    def mouseReleaseEvent(self, event):
        """ 无边框可移动组件3 """
        self.mouse_flag = False
